package com.chuangyang.fixboxmaster.ui.fragment.orderprice;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;

import com.android.volley.Response;
import com.chuangyang.fixboxlib.widgets.PullDownRefreshListView;
import com.chuangyang.fixboxmaster.R;
import com.chuangyang.fixboxmaster.bean.CostItem;
import com.chuangyang.fixboxmaster.bean.Part;
import com.chuangyang.fixboxmaster.bean.PartInfo;
import com.chuangyang.fixboxmaster.service.FixBoxApi;
import com.chuangyang.fixboxmaster.service.GsonRequest;
import com.chuangyang.fixboxmaster.ui.AddPartActivity;
import com.chuangyang.fixboxmaster.ui.ApplianceInfoActivity;
import com.chuangyang.fixboxmaster.ui.ModuleActivity;
import com.chuangyang.fixboxmaster.ui.adapter.PartListAdapter;
import com.chuangyang.fixboxmaster.ui.fragment.BaseFragment;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

/**
 * Created by Administrator on 2015/6/10.
 */
public class PartFragment extends BaseFragment implements AdapterView.OnItemClickListener,View.OnClickListener,PullDownRefreshListView.OnRefreshListener{

    private View mContentView;
    private PullDownRefreshListView mPartListView;
    private PartListAdapter mAdapter;
    private ArrayList<Part> mParts = new ArrayList<>();

    private ArrayList<Part> mSelectParts = new ArrayList<>();

    private String mTransactionId;

    private String mSpecificationId;

    private Button mConfirmView;

    private String mOrderID;

    private String mProductDate;

    private String mBrandId;

    public static final int REQUEST_CODE_ADD_PART = 1;

    private boolean bFinish = false;

    private String mSearchInput = "";

    private CostItem mRepairTYpe;

    private ArrayList<CostItem> mTypeList = new ArrayList<>();


    public static PartFragment newInstance(){
        return new PartFragment();
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mContentView = inflater.inflate(R.layout.fragment_part,container,false);
        Bundle bundle = new Bundle();
        bundle = getArguments();
        mTransactionId = bundle.getString(ApplianceInfoActivity.TRANSCATION_ID);
        mSpecificationId = bundle.getString(ApplianceInfoActivity.SPECIFICATION_ID);
        mOrderID = bundle.getString(ApplianceInfoActivity.ORDER_ID);
        mProductDate = getArguments().getString(ModuleActivity.PRODUCT_DATE);
        mBrandId = getArguments().getString(ModuleActivity.BRAND_ID);
        Object object = getArguments().getSerializable(ApplianceInfoActivity.SELECT_PART);
        mRepairTYpe = (CostItem)bundle.getSerializable(ModuleActivity.REPAIR_TYPE);
        mTypeList = (ArrayList<CostItem>)bundle.getSerializable(ModuleActivity.COST_ITEM);
        if (object != null)
        {
            mSelectParts = (ArrayList<Part>)object;
            if (mSelectParts != null)
                bFinish = true;
        }

        initView();
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setContentView(mContentView);
        loadData();
    }

    private void initView(){
        mPartListView = (PullDownRefreshListView)mContentView.findViewById(R.id.part_list);
        mAdapter = new PartListAdapter(mParts);
        mPartListView.setAdapter(mAdapter);
        mPartListView.setOnItemClickListener(this);
        mConfirmView = (Button)mContentView.findViewById(R.id.btn_ok);
        mConfirmView.setOnClickListener(this);
        mPartListView.setOnRefreshListener(this);
    }

    private void loadData(){
        mPartListView.setLoading();
        HashMap<String, String> param = new HashMap<>();
        param.put("transactionId", mTransactionId);
        param.put("specificationId", mSpecificationId);
        param.put("pageIndex", String.valueOf(mParts.size()));
        if (mSearchInput != null && !mSearchInput.trim().equals(""))
            param.put("keyword", mSearchInput.trim());
        addRequest(new GsonRequest<>(FixBoxApi.GET_PART, param, PartInfo.class, responseListener));

    }


    private Response.Listener<PartInfo> responseListener = new Response.Listener<PartInfo>() {
        @Override
        public void onResponse(PartInfo response) {
            if (response.result != null)
            {
                mParts.addAll(Arrays.asList(response.result.lists));
                replaceParts();
                showResult();
                if (mParts.size() >= response.result.totalCount)
                {
                    for (Part part:mSelectParts)
                    {
                        if (!mParts.contains(part))
                        {
                            mParts.add(part);
                        }
                    }
                    mPartListView.setLoadingEnd();
                }
                else
                {
                    mPartListView.setLoadingIdle();
                }
                mAdapter.setmBrandsTemps(mParts);
                if (mSearchInput != null && !mSearchInput.trim().equals(""))
                    mAdapter.filter(mSearchInput);
                mAdapter.notifyDataSetChanged();
            }
        }
    };

    private void replaceParts(){

        if (mSelectParts == null || mSelectParts.size() <= 0)
            return;
        for (int i = 0; i < mParts.size(); i++)
        {
            Part part = mParts.get(i);

            for (Part part1:mSelectParts)
            {
                if (part.id == part1.id)
                {
                    mParts.set(i,part1);
                    break;
                }
            }
        }
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        Part part = mParts.get(position);
        if (part != null)
        {
            part.bSelect = !part.bSelect;
            mAdapter.notifyDataSetChanged();
            if (part.bSelect)
            {
                part.num = 1;
                mSelectParts.add(part);
            }
            else
            {
                part.num = 0;
                mSelectParts.remove(part);
            }
        }
    }

    public void addPart(){
        Intent intent = new Intent(getActivity(), AddPartActivity.class);
        startActivityForResult(intent,REQUEST_CODE_ADD_PART);
    }


    @Override
    public void onClick(View v) {

        switch (v.getId())
        {
            case R.id.btn_ok:
                if (!bFinish)
                {
                    if (mSelectParts != null && mSelectParts.size() > 0)
                    {
                        Intent intent = new Intent(getActivity(),ModuleActivity.class);
                        Bundle bundle = new Bundle();
                        bundle.putSerializable(ModuleActivity.SELECT_PART,mSelectParts);
                        bundle.putSerializable(ModuleActivity.REPAIR_TYPE, mRepairTYpe);
                        bundle.putSerializable(ModuleActivity.COST_ITEM,mTypeList);
                        bundle.putInt(ApplianceInfoActivity.TYPE, ModuleActivity.APPLIANCE_PRICE_ACTIVITY);
                        bundle.putString(ApplianceInfoActivity.ORDER_ID,mOrderID);
                        bundle.putString(ApplianceInfoActivity.TRANSCATION_ID,mTransactionId);
                        bundle.putString(ApplianceInfoActivity.SPECIFICATION_ID,mSpecificationId);
                        bundle.putString(ApplianceInfoActivity.PRODUCT_DATE,mProductDate);
                        bundle.putString(ApplianceInfoActivity.BRAND_ID,mBrandId);
                        intent.putExtras(bundle);
                        startActivity(intent);
                    }
                    getActivity().finish();
                }
                else
                {
                    Intent intent = new Intent();
                    Bundle bundle = new Bundle();
                    bundle.putSerializable(ModuleActivity.SELECT_PART,mSelectParts);
                    intent.putExtras(bundle);
                    getActivity().setResult(Activity.RESULT_OK,intent);
                    getActivity().finish();
                }
                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode)
        {
            case  REQUEST_CODE_ADD_PART:

                if (data != null)
                {

                    Bundle bundle = data.getExtras();
                    if (bundle != null)
                    {
                        Part part = (Part)bundle.getSerializable("part");
                        if (part != null)
                        {
                            part.num = 1;
                            if (part.fixPrice <= 0)
                                part.fixPrice = mRepairTYpe.price;
                            mSelectParts.add(part);
                            mParts.add(part);
                            mAdapter.addBrand(part);
                            mAdapter.notifyDataSetChanged();
                            mAdapter.filter(mSearchInput);
                        }
                    }
                }
                break;
        }
    }

    public void doSearch() {
        mParts.clear();
        mPartListView.setAdapter(mAdapter);
        loadData();
    }

    public TextWatcher getTextWatcher(){

        return new TextWatcher(){

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                mSearchInput = s.toString();
            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        };


    }

    public void updateListView() {
        mParts.clear();
        mPartListView.setAdapter(mAdapter);
        loadData();
    }

    @Override
    public ListView getListView() {
        return mPartListView;
    }

    @Override
    public void onRefresh() {
        loadData();
    }
}
